package developer.算法.图论.岛屿数量;

/**
 * @author zhangyongkang
 * @time 2025/3/31 15:50
 * @description 给你一个由 '1'（陆地）和 '0'（水）组成的的二维网格，请你计算网格中岛屿的数量。
 * <p>
 * 岛屿总是被水包围，并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
 * <p>
 * 此外，你可以假设该网格的四条边均被水包围。
 * <p>
 * <p>
 * <p>
 * 示例 1：
 * <p>
 * 输入：grid = [
 * ["1","1","1","1","0"],
 * ["1","1","0","1","0"],
 * ["1","1","0","0","0"],
 * ["0","0","0","0","0"]
 * ]
 * 输出：1
 * <p>
 * 示例 2：
 * <p>
 * 输入：grid = [
 * ["1","1","0","0","0"],
 * ["1","1","0","0","0"],
 * ["0","0","1","0","0"],
 * ["0","0","0","1","1"]
 * ]
 * 输出：3
 */
public class DaoYuShuLiang {
    public static void main(String[] args) {
        Solution solution = new Solution();
        char[][] grid = {
                {'1', '1', '1', '1', '0'},
                {'1', '1', '0', '1', '0'},
                {'1', '1', '0', '0', '0'},
                {'0', '0', '0', '0', '0'},
        };
        int i = solution.numIslands(grid);
        System.out.println(i);
    }

    static class Solution {
        public int numIslands(char[][] grid) {
            int result = 0;
            int rowLength = grid.length;
            int colLength = grid[0].length;
            //遍历所有节点，如果当前节点为1  则将关联的节点为1 的都置0
            //意思是 将一片大陆 浓缩为一个1
            for (int i = 0; i < rowLength; i++) {
                for (int j = 0; j < colLength; j++) {
                    if (grid[i][j] == '1') {
                        dfs(grid, i, j);
                        result++;
                    }
                }
            }
            return result;
        }

        public void dfs(char[][] grid, int row, int col) {
            if (!isInArea(row, col, grid)) {
                return;
            }
            char cell = grid[row][col];
            if (cell == '0') {
                return;
            }
            grid[row][col] = '0';
            dfs(grid, row - 1, col);
            dfs(grid, row + 1, col);
            dfs(grid, row, col - 1);
            dfs(grid, row, col + 1);
        }

        public boolean isInArea(int row, int col, char[][] gird) {
            return row < gird.length
                    && row >= 0
                    && col < gird[0].length
                    && col >= 0;
        }
    }
}
